﻿
Imports System.Threading
Imports osi.root.connector
Imports osi.root.envs
Imports lock_t = osi.root.lock.slimlock.monitorlock

'multi writer / multi reader model
'lock / unlock is for writer, which will also have a sequentialLock to protect.
'wait / release is for reader, suppose reader will not change, but only read, so no protection needed.
'readers will not block other readers, except for fl check & sl increment / decrement
'writers will block other writers, meanwhile any readers
Public Structure duallock
    Private fl As lock_t
    Private sl As Int32

    Shared Sub New()
        k_assert(DirectCast(Nothing, Int32) = 0)
    End Sub

    Public Sub lock()
        fl.wait()
        lazy_wait_when(Function(ByRef x) x > 0, sl)
    End Sub

    Public Sub unlock()
        k_assert(sl = 0)
        fl.release()
    End Sub

    Public Sub writer_wait()
        lock()
    End Sub

    Public Sub writer_release()
        unlock()
    End Sub

    Public Sub wait()
        fl.wait()
        Interlocked.Increment(sl)
        fl.release()
    End Sub

    Public Sub release()
        Interlocked.Decrement(sl)
    End Sub

    Public Sub reader_wait()
        wait()
    End Sub

    Public Sub reader_release()
        release()
    End Sub
End Structure
